#include <iostream>
#include <cstring>
#include <vector>
#include <pthread.h>
#include <unistd.h>

using namespace std;

int tickets = 1000;
class ThreadData
{
public:
    ThreadData(const string& thread_name)//, pthread_mutex_t* mutex_p
    :_thread_name(thread_name)
    // ,_mutex_p(mutex_p)
    {}
    ~ThreadData()
    {}
public:
    const string _thread_name;
    // pthread_mutex_t* _mutex_p;
};

void* get_tickets(void* args)
{
    // string name = static_cast<const char*>(args);
    ThreadData *td = static_cast<ThreadData *>(args);
    while(1)
    {
        if(tickets > 0)
        {
            cout << td->_thread_name << " 正在抢票 : " << tickets << endl;
            // cout << name << " 正在抢票 : " << tickets << endl;
            tickets--;
            sleep(1);
        }
        else
        {
            break;
        }
    }
    return nullptr;
}

int main()
{
#define NUM 4
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock, nullptr);
    vector<pthread_t> tids(NUM);
    for(int i = 0; i < NUM; i++)
    {
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "thread %d", i+1);
        ThreadData* td = new ThreadData(buffer);
        pthread_create(&tids[i], nullptr, get_tickets, td);
    }

    // while(1)
    // {
    //     cout << " main running ....." << endl;
    //     sleep(1);
    // }

    for(auto& iter : tids)
    {
        pthread_join(iter, nullptr);
    }
    return 0;
}